import api from "@/api/api";
/**
 * 享停车·路内
 */
import Vue from "vue";
var QRCoder = null;
const resultCallbackMap = new Map();
var userValue;
const KEYROLE = "a-a";
const KEYVALUE = "a-b";
export default {
    homeComponent: null,
    invoiceData: null, // 发票订单选取的临时数据列表
    invoiceContentData: null, // 企业发票--填写更多内容的临时数据
    isInspection: false, // 路段是否是巡检车模式
    isApplyOrderChange: false, // 异常申请是否通过

    /**
     * @override 调用api.clearAccountCache时，自动调用此方法
     */
    clearAccountCache() {
        resultCallbackMap.clear();
        userValue = null;
        this.homeComponent = null;
    },

    // 获取收费的二维码
    getRoadQrCode(data, callback) {
        if (!data) {
            callback(null);
            return;
        }
        let url;
        let prefix = "";
        let array = data.split(";");
        if (array.length == 2) {
            url = array[0];
            prefix = array[1] + ":";
        } else {
            url = data;
        }
        let index = url.indexOf("b=");
        if (index > -1) {
            url = url.substring(index + 2, url.length);
        }
        let result = api.getAppConfig().getWebUrl() + "?b=qr:" + prefix + url;
        if (!QRCoder) {
            QRCoder = require("../utils/qrcode.js");
        }
        let imageSrc = "";
        // imageSrc = require("../assets/images/ic_logo.png");
        QRCoder.requestQrUrl(result, imageSrc, 430, "使用微信或支付宝扫码支付", callback);
    },

    getRoadRecoverQrCode(data, callback) {
        if (!data) {
            callback(null);
            return;
        }
        let url;
        let prefix = "";
        let array = data.split(";");
        if (array.length == 2) {
            url = array[0];
            prefix = array[1] + ":";
        } else {
            url = data;
        }
        let index = url.indexOf("b=");
        if (index > -1) {
            url = url.substring(index + 2, url.length);
        }
        let result = api.getAppConfig().getWebUrl() + "?b=recover:" + prefix + url;
        if (!QRCoder) {
            QRCoder = require("../utils/qrcode.js");
        }
        let imageSrc = "";
        // imageSrc = require("../assets/images/ic_logo.png");
        QRCoder.requestQrUrl(result, imageSrc, 430, "使用微信或支付宝扫码支付", callback);
    },

    /**
     * @override 自动清除本地数据时，自动调用此方法
     */
    clearAppCache(callback) {
        checkApp("clearValue", null, callback);
    },

    /**
     * @override 调用api.setAccountCache时，自动调用此方法
     */
    setAppCache(key, value) {
        notifyApp("addValue", key, value);
    },

    /**
     * @override 调用api.setAccountCache时，自动调用此方法
     */
    removeAppCache(key) {
        notifyApp("removeValue", key);
    },

    /**
     * @override 调用api.setClipboardData时，自动调用此方法
     */
    setClipboardData(text, callback) {
        checkApp("setClipboard", text, function(error) {
            if (error) {
                callback(false, error);
            } else {
                callback(true, null);
            }
        });
    },

    /**
     * @override 调用api.getClipboardData时，自动调用此方法
     */
    getClipboardData(callback) {
        checkApp("getClipboard", null, function(data) {
            callback(true, data);
        });
    },

    /**
     * @override 调用api.getLocation时，自动调用此方法
     */
    getLocation(isShowLoading, callback) {
        if (isShowLoading) {
            api.showLoading();
        }
        checkApp("getLocation", null, function(data) {
            if (isShowLoading) {
                api.hideLoading();
            }
            if (data && typeof data == "object") {
                callback(true, data);
            } else {
                callback(false, data);
            }
        });
    },

    /**
     * 获取用户角色数据
     * @return {Object} data
     * data.name 用户名称
     * data.entityName 商家名称
     * data.roleName 角色名称
     * data.linkId	
     * data.roleId
     * data.areaList 路段列表
     * [{
     *	 areaId 路段code
     * 	 areaName 路段名称
     * }]
     */
    getAccountValueSync() {
        if (userValue) {
            return userValue;
        }
        return api.getAccountCache(KEYVALUE);
    },

    postRoleUrl(isShowLoading, url, param) {
        let value = this.getAccountValueSync();
        if (value && value.requestUrl) {
            return api.postUrl(isShowLoading, value.requestUrl + url, param);
        } else {
            this.jumpLoginPage();
            return new Promise(function(resolve, reject) {
                reject("请重新登录");
            });
        }
    },

    getRoleUrl(isShowLoading, url, param) {
        let value = this.getAccountValueSync();
        if (value && value.requestUrl) {
            return api.getUrl(isShowLoading, value.requestUrl + url, param);
        } else {
            this.jumpLoginPage();
            return new Promise(function(resolve, reject) {
                reject("请重新登录");
            });
        }
    },

    loginRole(item) {
        return new Promise(function(resolve, reject) {
            // api.getUrl(true, api.getAppConfig().getNetHeadUrl() + "/manager/url/" + item.linkId + "?areaIds=" + item.areaInfo).then(function (data) {
            //   if (data && data.serverUrl) {
            //     userValue = item;
            //     userValue.requestUrl = data.serverUrl;
            //     userValue.areaList = data.areaList;
            //     api.setAccountCache(KEYVALUE, userValue);
            //     resolve(true);
            //   } else {
            //     reject("暂无可用的数据");
            //   }
            // }).catch(function (reason) {
            //   reject(reason);
            // });
        });
    },

    getAccountRoleSync() {
        return api.getAccountCache(KEYROLE);
    },

    saveAccountRole(roleList) {
        api.setAccountCache(KEYROLE, roleList);
    },

    // 缓存首页的实例
    setHomeInstance(component) {
        this.homeComponent = component;
    },

    refreshLot() {
        if (this.homeComponent && this.homeComponent.refreshLot) {
            this.homeComponent.refreshLot(true);
        }
    },

    refreshLotRoad(selectItem) {
        if (this.homeComponent && this.homeComponent.refreshLotRoad) {
            this.homeComponent.refreshLotRoad(selectItem);
        }
    },

    refreshMsg() {
        if (this.homeComponent && this.homeComponent.refreshMsg) {
            this.homeComponent.refreshMsg(true);
        }
    },

    refreshRepairing() {
        if (this.homeComponent && this.homeComponent.refreshRepairing) {
            this.homeComponent.refreshRepairing();
        }
    },

    refreshNeedRepair() {
        if (this.homeComponent && this.homeComponent.refreshNeedRepair) {
            this.homeComponent.refreshNeedRepair();
        }
    },

    getCurrentPages() {
        if (Vue.instance.$children && Vue.instance.$children[0]) {
            return Vue.instance.$children[0].$children;
        }
        return null;
    },

    jumpLoginPage() {
        api.jumpPage("Login", {
            reload: true
        }, true);
    },

    reloadWindow() {
        // if (window.zkroad) {
        //   window.zkroad.setWebRequest("reloadWindow", null, 0);
        // } else {
        window.location.reload();
        // }
    },

    restartApp() {
        notifyApp("restartApp");
    },

    exitApp() {
        notifyApp("exitApp");
    },

    updateVersion() {
        notifyApp("updateVersion");
    },

    notifyMsg(title, content) {
        notifyApp("notifyMsg", title, content);
    },

    ttsMsg(title) {
        notifyApp("ttsMsg", title);
    },

    stopPullDownRefresh() {
        notifyApp("stopPullDown");
    },

    enableRefresh(enable) {
        notifyApp("enableRefresh", enable);
    },

    initAppCache(callback) {
        checkApp("initValue", null, callback);
    },

    checkDevice(callback) {
        checkApp("checkDevice", null, callback);
    },

    startCamera(param, callback) {
        checkApp("startCamera", param, callback);
    },

    checkCamera(callback) {
        checkApp("checkCamera", null, callback);
    },

    printTicket(param, callback) {
        checkApp("printTicket", param, callback);
    },

    deleteSystemCameraFile(callback) {
        checkApp("deleteSystemCamera", null, callback);
    },

    startScan(callback) {
        checkApp("startScan", null, callback);
    },

    onActivityResult(requestCode, key, value) {
        if (key == "onKeyDown") {
            let pageList = this.getCurrentPages();
            if (pageList && pageList.length > 0) {
                let page = pageList[pageList.length - 1];
                try {
                    page = page.$children[0].$children[0];
                } catch (error) {}
                if (page && page.onKeyDownResult && page.onKeyDownResult()) {
                    return;
                }
            }
            api.finishPage();
        } else if (key == "onPullDown") {
            let pageList = this.getCurrentPages();
            if (pageList && pageList.length > 0) {
                let page = pageList[pageList.length - 1];
                try {
                    page = page.$children[0].$children[0];
                } catch (error) {}
                if (page && page.onPullDownRefresh) {
                    page.onPullDownRefresh();
                    return;
                }
            }
            notifyApp("stopPullDown");
        } else if (key == "initValue") {
            sessionStorage.clear();
            if (value && value != "null") {
                try {
                    let valueObj = JSON.parse(value);
                    if (valueObj) {
                        for (let key in valueObj) {
                            let item = valueObj[key];
                            if (item != undefined && item != null) {
                                sessionStorage.setItem(key, item);
                            }
                        }
                    }
                } catch (e) {
                    api.log("initValue", e);
                }
            }
            api.initStorage();
            let callback = resultCallbackMap.get(requestCode);
            if (callback) {
                resultCallbackMap.delete(requestCode);
                callback();
            }
        } else {
            let callback = resultCallbackMap.get(requestCode);
            if (callback) {
                resultCallbackMap.delete(requestCode);
                if (value == "null") {
                    callback();
                    return;
                }
                if (typeof value == "string") {
                    try {
                        let result = JSON.parse(value);
                        if (typeof result == "object") {
                            callback(result);
                            return;
                        }
                    } catch (e) {}
                }
                callback(value);
            }
        }
    }
}

function notifyApp(ins, param, requestCode) {
    if (window.zkroad) {
        if (param == undefined) {
            param = null;
        }
        if (requestCode == undefined || requestCode == null) {
            requestCode = 0;
        }
        window.zkroad.setWebRequest(ins, param, requestCode);
    }
}

function checkApp(ins, param, callback) {
    // if (window.zkroad) {
    //   let realParam = param;
    //   if (typeof (param) != "string") {
    //     try {
    //       realParam = JSON.stringify(param);
    //     } catch (e) {
    //       api.log(e);
    //     }
    //   }
    //   let requestCode = new Date().getTime() + "";
    //   if (callback) {
    //     resultCallbackMap.set(requestCode, callback);
    //   }
    //   window.zkroad.setWebRequest(ins, realParam, requestCode);
    // } else {
    if (callback) {
        callback();
    }
    // }
}